from flask import current_app, g
from flask_restful import marshal, Resource

from libs.tools import response
from apps.models.user import User
from apps.logics.admin.user import filter_users
from apps.entities.admin.user import create_user_parser, filter_user_parser
from apps.entities.admin.user import response_user_fields


class UsersView(Resource):

    def get(self):
        params = filter_user_parser.parse_args()
        users = User.list()
        users = filter_users(users, params, g)
        data = marshal(users.all(), response_user_fields)
        return response(status_code=200, data=data)

    def post(self):
        params = create_user_parser.parse_args()
        user = User(creator=g.user.id, **params)
        user.save()
        return response(status_code=201, data=user.id)


class UserView(Resource):

    def get(self, user_id):
        user = User.get(id=user_id)
        if user:
            return response(status_code=200, data=marshal(user, response_user_fields))
        else:
            return response(status_code=404, msg=f'cant not find user by id = {user_id}')
